﻿using DryIoc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using HtmlAgilityPack;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using Prism.Mvvm;
using HandyControl.Controls;
using Newtonsoft.Json.Linq;

namespace qubaohe.ViewModels
{
    public class SongDownloadModel : BindableBase
    {


        private readonly HttpClient _httpClient = new HttpClient();
        public ObservableCollection<SongItem> Songs { get; } = new ObservableCollection<SongItem>();

        private string _searchKeyword;
        public string SearchKeyword
        {
            get => _searchKeyword;
            set => SetProperty(ref _searchKeyword, value);


        }

        public SongDownloadModel(string keyword)
        {
            SearchKeyword = keyword;
        }



        public async Task<string> GetStringAsync(string songname)
        {
            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"https://www.gequbao.com/s/{songname}");

            request.Headers.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
            request.Headers.Add("accept-language", "zh-CN,zh;q=0.9");
            request.Headers.Add("cache-control", "no-cache");
            request.Headers.Add("pragma", "no-cache");
            request.Headers.Add("priority", "u=0, i");
            request.Headers.Add("referer", songname);
            request.Headers.Add("sec-ch-ua", "\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Google Chrome\";v=\"134\"");
            request.Headers.Add("sec-ch-ua-mobile", "?0");
            request.Headers.Add("sec-ch-ua-platform", "\"Windows\"");
            request.Headers.Add("sec-fetch-dest", "document");
            request.Headers.Add("sec-fetch-mode", "navigate");
            request.Headers.Add("sec-fetch-site", "same-origin");
            request.Headers.Add("sec-fetch-user", "?1");
            request.Headers.Add("upgrade-insecure-requests", "1");
            request.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36");
            request.Headers.Add("cookie", "Hm_tf_t8h1bavogbi=1742247225; Hm_lvt_t8h1bavogbi=1742247225; Hm_lpvt_t8h1bavogbi=1742248406");

            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();

            //Debug.WriteLine(responseBody);

            return responseBody;
        }
        public async Task<ObservableCollection<SongItem>> SearchSongsAsync()
        {

            return await Task.Run(async () =>
            {

                try
                {


                    var response = await GetStringAsync(SearchKeyword);
                    var doc = new HtmlDocument();
                    doc.LoadHtml(response);

                    var nodes = doc.DocumentNode.SelectNodes("//div[@class='row']/div[1]/a");
                    if (nodes == null) return Songs;
                    Debug.WriteLine(nodes.Count);


                    int id = 1;
                    foreach (var node in nodes)
                    {
                        var songName = WebUtility.HtmlDecode(node.SelectNodes("span")[0].InnerText)
                            .Replace("\n", "").Replace(" ", "");
                        var author = WebUtility.HtmlDecode(node.SelectNodes("small")[0].InnerText)
                         .Replace("\n", "").Replace(" ", "");

                        var songUrl = "https://www.gequbao.com" + node.GetAttributeValue("href", "");





                        Songs.Add(new SongItem
                        {
                            Id = id++,
                            SongName = songName,
                            Author = author,
                            DownloadProgress = 0,
                            IsSelected = false,
                            Url = songUrl,

                        });
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"搜索失败: {ex.Message}");
                }
                return Songs;
            });
        }

        public async Task<string> GetDownloadUrlAsync(string url)
        {
            try
            {
                var response = await _httpClient.GetStringAsync(url);
                var match = Regex.Match(response, @"window.play_id = '(.*?)';");
                if (!match.Success) return null;

                var content = new FormUrlEncodedContent(new[]
                {
                new KeyValuePair<string, string>("id", match.Groups[1].Value)
            });

                var result = await _httpClient.PostAsync("https://www.gequbao.com/api/play-url", content);
                var json = await result.Content.ReadAsStringAsync();
                return JObject.Parse(json)["data"]?["url"]?.ToString();
            }
            catch
            {
                return null;
            }
        }

        public async Task DownloadFileAsync(SongItem song, string savePath)
        {
            try
            {
                using (var response = await _httpClient.GetAsync(song.DownloadUrl, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();

                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                    {
                        var buffer = new byte[8192];
                        int bytesRead;
                        long totalBytesRead = 0;
                        long? totalBytes = response.Content.Headers.ContentLength;

                        while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await fileStream.WriteAsync(buffer, 0, bytesRead);
                            totalBytesRead += bytesRead;

                            // 更新进度逻辑
                            if (totalBytes.HasValue)
                            {
                                song.DownloadProgress = (int)((double)totalBytesRead / totalBytes.Value * 100);
                                //RaisePropertyChanged(nameof(Songs));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 异常处理
                Debug.WriteLine($"下载失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 下载歌词
        /// </summary>
        /// <returns></returns>
        public async Task DownloadLyricAsync(SongItem song, string savePath) 
        { 

            try
            {
                var response = await _httpClient.GetAsync(song.Url, HttpCompletionOption.ResponseHeadersRead);
                response.EnsureSuccessStatusCode();
                var content = await response.Content.ReadAsStringAsync();
                var doc = new HtmlDocument();
                doc.LoadHtml(content);

                //  //*[@id="content-lrc"]
                var nodes = doc.DocumentNode.SelectNodes("//*[@id=\"content-lrc\"]");
                if (nodes == null) return;
                var lyric = nodes[0].InnerText;
                
                File.WriteAllText(savePath, lyric);
                
            }
            catch (Exception ex)
            {
                // 异常处理
                Debug.WriteLine($"下载歌词失败: {ex.Message}");
            }   
            
        
        }




    }
}
